package cn.thens.kdroid.vcs.revison

import org.codehaus.groovy.runtime.ProcessGroovyMethods
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.ByteArrayOutputStream
import java.util.regex.Pattern

class VcsRevisionPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        val vcsRevision = getVcsRevision(project.rootProject)
        println("vcs-revision: $vcsRevision")
        project.extensions.add("vcsRevision", vcsRevision)
    }

    private fun getVcsRevision(project: Project): Int {
        return try {
            getGitRevision(project)
        } catch (gitException: Exception) {
            try {
                getSvnRevision(project)
            } catch (svnException: Exception) {
                println(gitException.message)
                println(svnException.message)
                1
            }
        }
    }

    @Suppress("UNUSED_PARAMETER")
    private fun getGitRevision(project: Project): Int {
        val outputText = execute("git rev-list HEAD --count")
        return try {
            outputText.toInt()
        } catch (e: Exception) {
            throw RuntimeException("unable to fetch git revision: $outputText")
        }
    }

    @Suppress("UNUSED_PARAMETER")
    private fun getSvnRevision(project: Project): Int {
        val outputText = execute("svn info")
        val pattern = Pattern.compile("(最后修改的版本:|Last Changed Rev:) (\\d+)")
        val lastChangedRevMatcher = pattern.matcher(outputText)
        if (lastChangedRevMatcher.find()) {
            return lastChangedRevMatcher.group(2).toInt()
        }
        throw RuntimeException("unable to fetch svn revision: $outputText")
    }

    private fun execute(command: String): String {
        val process = ProcessGroovyMethods.execute(command)
        return ProcessGroovyMethods.getText(process).trim()
    }
}